package com.sc.auction.order.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.auction.common.pojo.Auction;
import com.sc.auction.common.pojo.Goods;
import com.sc.auction.common.pojo.Images;
import com.sc.auction.common.pojo.User;
import com.sc.auction.common.util.OrderUtil;
import com.sc.auction.common.util.R;
import com.sc.auction.order.feign.AuctionFeignService;
import com.sc.auction.order.feign.GoodsFeignService;
import com.sc.auction.order.feign.UserFeignService;
import com.sc.auction.order.pojo.Orders;
import com.sc.auction.order.service.OrdersService;
import com.sc.auction.order.vo.OrderVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author theTi
 * @since 2020-09-11
 */
@RestController
@RequestMapping("/order/order")
@CrossOrigin
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private AuctionFeignService auctionFeignService;
    @Autowired
    private GoodsFeignService goodsFeignService;
    @Autowired
    private UserFeignService userFeignService;

    @PostMapping(value = "/getOrdersByPage")
    @ApiOperation("订单分页查询 可通过订单编号和状态查询")
    public R getOrdersByPage(@ApiParam(name = "page",defaultValue = "1",required = true)@RequestParam("page") Integer page,
                             @ApiParam(name = "limit",defaultValue = "5",required = true)@RequestParam("limit") Integer limit,
                             @RequestBody(required=false) Orders order){
        System.out.println(order);
        Page<Orders> pageBean=new Page<>(page,limit);
        QueryWrapper queryWrapper=null;
        if(order!=null) {
            //条件查询
            queryWrapper = new QueryWrapper();
            //根据订单编号查询
            if(order.getOrderno()!=null&&!order.getOrderno().isEmpty()){
                System.out.println(order.getOrderno());
                queryWrapper.eq("orderno",order.getOrderno());
            }
            //根据订单状态查询
            if(order.getStatus()!=null){
                queryWrapper.eq("status",order.getStatus());
            }
        }
        ordersService.page(pageBean,queryWrapper);
        //查到基础订单信息
        List<Orders> records = pageBean.getRecords();
        //创建新集合 遍历基础订单信息 查询额外信息
        List<OrderVo> orderVos = new ArrayList<>();
        for(Orders order1:records){
            OrderVo orderVo = getOrderVo(order1);
            orderVos.add(orderVo);
        }
        long total = pageBean.getTotal();

        if (records!=null&&records.size()>0){
            return R.ok().data("total",total).data("records",orderVos);
        }else {
            return R.error();
        }
    }

    @PostMapping(value = "/getOrdersByUserid")
    @ApiOperation("通过userid订单分页查询")
    public R getOrdersByUserid(@ApiParam(name = "page",defaultValue = "1",required = true)@RequestParam("page") Integer page,
                               @ApiParam(name = "limit",defaultValue = "5",required = true)@RequestParam("limit") Integer limit,
                               Orders order){
        Page<Orders> pageBean=new Page<>(page,limit);
        QueryWrapper queryWrapper= new QueryWrapper();
        queryWrapper.eq("userid",order.getUserid());
            //根据订单编号查询
            if(order.getOrderno()!=null&&!order.getOrderno().isEmpty()){
                System.out.println(order.getOrderno());
                queryWrapper.like("orderno",order.getOrderno());
            }
        ordersService.page(pageBean,queryWrapper);
        //查到基础订单信息
        List<Orders> records = pageBean.getRecords();
        //创建新集合 遍历基础订单信息 查询额外信息
        List<OrderVo> orderVos = new ArrayList<>();
        for(Orders order1:records){
            OrderVo orderVo = getOrderVo(order1);
            orderVos.add(orderVo);
        }
        long total = pageBean.getTotal();

        if (records!=null&&records.size()>0){
            return R.ok().data("total",total).data("records",orderVos);
        }else {
            return R.error();
        }
    }

    @GetMapping(value = "/getOrderByid")
    @ApiOperation("根据id查询订单")
    public R getOrderByid(Integer id){
        Orders order = ordersService.getById(id);
        if(order!=null){
            OrderVo orderVo =getOrderVo(order);
            return R.ok().data("order",orderVo);
        }else {
            return R.error();
        }
    }

    @GetMapping(value = "/getOrderByAuctionId")
    @ApiOperation("根据Auctionid查询订单")
    public R getOrderByAuctionId(@RequestParam("id")Integer id){
        Orders order =null;
        if(id!=null){
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("auctionid",id);
            order = ordersService.getOne(queryWrapper);
        }
        if(order!=null){
            OrderVo orderVo = getOrderVo(order);
            return R.ok().data("order",orderVo);
        }else {
            return R.error();
        }
    }

    @ApiOperation("根据订单编号修改订单状态")
    @PutMapping(value = "/updateOrderStatusByOrderNo")
    public R updateOrderStatusByOrderNo(@RequestParam("orderno") String orderno,@RequestParam("status") Integer status){
        QueryWrapper queryWrapper = new QueryWrapper();
        if(orderno!=null&&!orderno.isEmpty()&&status!=null){
            queryWrapper.eq("orderno",orderno);
        }
        Orders orders=ordersService.getOne(queryWrapper);
        QueryWrapper queryWrapper1=new QueryWrapper();
        boolean b=false;
        if(orders!=null){
            //修改状态
            orders.setStatus(status);
            //更新更改时间
            orders.setModifyDate(new Date());
            queryWrapper1.eq("id",orders.getId());
            b = ordersService.update(orders,queryWrapper1);
        }
        if(b){
            return R.ok();
        }else {
            return R.error();
        }
    }
    @PutMapping(value = "/updateOrder")
    @ApiOperation("根据订单id修改订单")
    public R updateOrder(@RequestBody Orders orders){
        QueryWrapper queryWrapper = new QueryWrapper();
        if(orders!=null){
            queryWrapper.eq("id",orders.getId());
            orders.setModifyDate(new Date());
        }
        boolean result = ordersService.update(orders,queryWrapper);
        if(result){
            return R.ok();
        }else {
            return R.error();
        }
    }


    @ApiOperation("增加订单")
    @PostMapping(value = "/insertOrder")
    public R insertOrder(@RequestParam("uid") Integer uid,@RequestParam("money") BigDecimal money, @RequestParam("auctionid")Integer auctionid){
        boolean result= false;
        Orders orders = new Orders();
        if(uid!=null&&money!=null&&auctionid!=null){
            orders.setOrderno(OrderUtil.getOrderCode());
            orders.setAuctionid(auctionid);
            orders.setMoney(money);
            //通过uid查询user对象
            R r =userFeignService.getUserById(uid);
            Object go=r.getData().get("user");
            User user = JSON.toJavaObject((JSONObject)go,User.class);
            //添加订单中用户相关信息
            orders.setUserid(user.getId());
            orders.setBuyer(user.getConsignee());
            orders.setAddress(user.getAddress());
            orders.setTelephone(user.getTelephone());
        }
        if(orders!=null){
            Date date = new Date();
            orders.setCreationDate(date);
            orders.setModifyDate(date);
            result=ordersService.save(orders);
        }
        if(result){
            return R.ok();
        }else {
            return R.error();
        }
    }
        @ApiOperation("删除订单")
        @DeleteMapping(value = "/deleteOrder")
        public R deleteOrder(@RequestParam("id") Integer id){
            boolean b = ordersService.removeById(id);
            if(b){
                return R.ok().code(200).message("删除订单成功！");
            }else{
                return R.error().code(201).message("删除订单失败");
            }
        }

    //传入orders 返回orderVo
    public OrderVo getOrderVo(Orders orders){
        System.out.println(orders);
        R r=auctionFeignService.getAuction(orders.getAuctionid());
        //得到拍品
        Object an = r.getData().get("auction");
        Auction auction=JSON.toJavaObject((JSONObject)an,Auction.class);
        //通过拍品获得商品
        Integer goodsid=auction.getGoodsId();
        R r2 =goodsFeignService.selectGoodsById(goodsid);
        Object go=r2.getData().get("goods");
        Goods goods = JSON.toJavaObject((JSONObject)go,Goods.class);

        OrderVo orderVo = new OrderVo();
        orderVo.setOrder(orders);
        //放入查询到的商品名称
        orderVo.setGoodsName(goods.getName());
        String goodsCode=goods.getGoodsCode();
        R r3=goodsFeignService.getImageByGoodsCode1(goodsCode);
        Object img=r3.getData().get("image");
        Images image=JSON.toJavaObject((JSONObject)img,Images.class);
        orderVo.setGoodsImage(image.getUrl());
        return orderVo;
    }
}

